/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useState } from 'react';
import { ChildLineCommandProps } from './types';

type FormDataType = {
  curve1: pickedLineData;
  curve2: pickedLineData;
  forward: number;
  back: number;
};

type Params = {
  curve1: string;
  curve2: string;
  forward: number;
  back: number;
};

export const Bisector = ({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) => {
  const initData: FormDataType = {
    curve1: null,
    curve2: null,
    forward: 60,
    back: 0,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { curve1, curve2, forward, back } = params;
    await initEditDependency([curve1, curve2]);
    setFormData({
      curve1: picker.generatePickObjByPickID(curve1) as pickedLineData,
      curve2: picker.generatePickObjByPickID(curve2) as pickedLineData,
      forward,
      back,
    });
  }, [editDxid]);

  const { picker } = useTools();

  const execute = (preview: boolean) => {
    const { curve1, curve2, forward, back } = formData;

    const params: Params = {
      curve1: curve1.edgeId,
      curve2: curve2.edgeId,
      forward,
      back,
    };

    return confirmCommand(
      {
        type: 'Line',
        a: {
          mode: 'bisector',
          ...params,
        },
      },
      preview,
    );
  };

  const isFormDataValid = () => {
    const { curve1, curve2, forward, back } = formData;

    return curve1 != null && curve2 != null && forward != null && back != null;
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    const { forward, back } = formData;
    if (forward === 0 && back === 0) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const checkAndFinishDraw = async () => {
    const { forward, back } = formData;
    if (forward === 0 && back === 0) {
      MessageTip.error('向前和向后不能同时为0');
      return;
    }

    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const {
    initEditDependency,
    initingEdit,
    confirmCommand,
    clear,
    isLoading,
    isPreviewLoading,
  } = useCommand('cmd-line-bisector', {
    commandName: 'CreateCurve',
    editDxid,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve1: {
        type: 'string',
        format: PickInputRJSFFormat.PickLine,
      },
      curve2: {
        type: 'string',
        format: PickInputRJSFFormat.PickLine,
      },
      forward: {
        type: 'number',
        title: '向前偏移',
        format: NumberInputFormat.Length,
      },
      back: {
        type: 'number',
        title: '向后偏移',
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      submitLoading={isLoading}
      previewLoading={isPreviewLoading}
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve1: {
          'ui:placeholder': '请输入直线1',
          'ui:autofocus': true,
        },
        curve2: {
          'ui:placeholder': '请输入直线2',
        },
        forward: {
          'ui:placeholder': '请输入向前偏移量',
        },
        back: {
          'ui:placeholder': '请输入向后偏移量',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
